<?php

class Translate_AdminController extends Ac_AdminController
{

    public function dashboardAction()
    {
        $this->view->num_untranslated_sc   = Model_Translate::all(array('zh_CN' => ''))->count();
        $this->view->num_untranslated_sc   += Model_Translate::all(array('zh_CN' => array('$exists' => false)))->count();

        $this->view->num_untranslated_tc   = Model_Translate::all(array('zh_HK' => ' '))->count();
        $this->view->num_untranslated_tc   += Model_Translate::all(array('zh_HK' => array('$exists' => false)))->count();
        
        $this->view->num_untranslated_jp   = Model_Translate::all(array('ja_JP' => ''))->count();
        $this->view->num_untranslated_jp   += Model_Translate::all(array('ja_JP' => array('$exists' => false)))->count();
    }

    public function menuAction()
    {
        $this->view->index = $this->_getParam('index');
    }

    public function indexAction() 
    {
        $this->listAction();
    }
    
    public function listAction() 
    {
        $per_page = 100;
        $page      = !empty($_GET['page']) ? $_GET['page'] : 1;
        $this->view->per_page = $per_page;
        $this->view->listing_number = Model_Translate::all()->count();
        $this->view->page = $page;

        if ($page>1) {
            $skip_page = ($_GET['page']-1) * $per_page;
        }
        
        if (!empty($_GET['search'])) {
            $term = new MongoRegex('/.*'.$_GET['search'].'.*/');
            if ($page>1) {
                $this->view->list           = Model_Translate::all(array('k' => $term))->skip($skip_page)->limit($per_page)->sort(array('k'=>1));
            }
            else {
                $this->view->list           = Model_Translate::all(array('k' => $term))->limit($per_page)->sort(array('zh_HK' => -1));
            }
            $this->view->listing_number = $this->view->list->count();
        }
        else {
            if ($page>1) {
                $this->view->list           = Model_Translate::all()->skip(($_GET['page']-1) * $per_page)->limit($per_page)->sort(array('k'=>1));
            }
            else {
                $this->view->list           = Model_Translate::all()->limit($per_page)->sort(array('zh_HK' => 1, 'c_dt' => -1));
            }
            $this->view->listing_number = $this->view->list->count();
        }
        
        $this->view->locales = Model_Translate::findLocales();
        $this->render('list');
    }
    
    public function editAction()
    {
        $key    = $_POST['id'];
        $value  = $_POST['val'];
        $locale = $_POST['loc'];
        Model_Translate::addTranslation($key, $value, $locale);
        echo 'ok';exit;
    }
    
    
    public function deleteAction()
    {
        $key    = $_GET['id'];
        Model_Translate::remove(array('_id'=>new MongoId($key)));
        $this->_redirect($_GET['refer']);
    }    
}